package com.wjk.girl.utils.wechat;

import com.wjk.girl.domain.wechat.AccessToken;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WeixinUtil {
    private static final String appId = "wxc2029dcf82fe40c8";
    private static final String appSecret = "8cd0ccc5ba3ff56709beb4d0cbe15f81";
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);
    protected static String OAUTH_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=req#wechat_redirect";
    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    public static JSONObject doGetStr(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String result = EntityUtils.toString(entity,"UTF-8");
                jsonObject = JSONObject.fromObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    public static JSONObject doPostStr(String url,String outStr){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonObject = null;
        httpPost.setEntity(new StringEntity(outStr,"UTF-8"));
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity(),"UTF-8");
            jsonObject = JSONObject.fromObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    public static AccessToken getAccessToken(){
        AccessToken accessToken = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID",appId).replace("APPSECRET",appSecret);
        JSONObject jsonObject = doGetStr(url);
        if(jsonObject != null){
            accessToken.setAccessToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getString("expires_in"));
        }
        return accessToken;
    }
    /**
    *@Autor 王帮主
    *@Description 获取网页授权url
    *@param
    *@Date: 9:17 2018/6/4
    */
    public static String getOpenidUrl() throws Exception {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String REDIRECT_URI = "http://wangjiankun.tunnel.echomod.cn/girl/wechat/getUserInfo";//你的回调页
        url = url.replace("APPID", appId);
        url = url.replace("STATE", "123");
        url = url.replace("REDIRECT_URI", REDIRECT_URI);

        return url;
    }
    public static Map<String,String> getOauth(String code) throws ParseException, IOException {

        Map<String,String> map = new HashMap<>();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
        url = url.replace("AppId", appId)
                .replace("AppSecret", appSecret)
                .replace("CODE", code);

        JSONObject obj = doGetStr(url);
        String openid = obj.getString("openid");
        String access_token = obj.getString("access_token");
        String expires_in = obj.getString("expires_in");
        String refresh_token = obj.getString("refresh_token");
        map.put("openid",openid);
        map.put("access_token",access_token);
        map.put("expires_in",expires_in);
        map.put("refresh_token",refresh_token);
        //检查access_token有效性
        int flag = checkAccessTokenValidate(access_token,openid);
        System.out.println("access_token时效性:"+flag);
        if(flag != 0){
            //发送refresh_token请求
            map = refreshToken(refresh_token);
        }
        return map;
    }
    public static Map<String,String> refreshToken(String refresh_token){
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
        url = url.replace("APPID",appId).
                replace("REFRESH_TOKEN",refresh_token);
        JSONObject obj = doGetStr(url);
        String openid = obj.getString("openid");
        String access_token = obj.getString("access_token");
        String expires_in = obj.getString("expires_in");
        refresh_token = obj.getString("refresh_token");
        Map<String,String> map = new HashMap<>();
        map.put("openid",openid);
        map.put("access_token",access_token);
        map.put("expires_in",expires_in);
        map.put("refresh_token",refresh_token);
        return map;
    }
    public static JSONObject getUserDetalsInfo(String access_token,String openid){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url = url.replace("ACCESS_TOKEN",access_token).
                replace("OPENID",openid);
        JSONObject obj = doGetStr(url);
        return obj;
    }
    public static int checkAccessTokenValidate(String access_token,String openid){
        String url = "https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID";
        url = url.replace("ACCESS_TOKEN",access_token).
                replace("OPENID",openid);
        JSONObject obj = doGetStr(url);
        int flag = obj.getInt("errcode");
        return flag;
    }

    /**
    *@Autor 王帮主
    *@Description 文件上传的方法
    *@param 
    *@Date: 15:26 2018/6/4
    */
    public static String upload(String filePath,String accessToken,String type) throws IOException {
        File file = new File(filePath);
        if(!file.exists() || !file.isFile()){
            throw new IOException("文件不存在！");
        }
        String url = UPLOAD_URL.replace("ACCESS_TOKEN",accessToken).replace("TYPE",type);
        URL urlObj = new URL(url);
        //连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST");
        //设置输入输出
        con.setDoInput(true);
        con.setDoOutput(true);
        //忽略缓存
        con.setUseCaches(false);
        //设置请求头信息
        con.setRequestProperty("Connection","Keep-Alive");
        con.setRequestProperty("Charset","UTF-8");
        //设置边界
        String BOUNDARY = "------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + BOUNDARY);

        StringBuffer sb = new StringBuffer();
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        //获得输入流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        //输出表头
        out.write(head);
        //文件正文部分
        //把文件以流文件的方式，推入到url中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1){
            out.write(bufferOut,0,bytes);
        }
        in.close();
        //结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分割线
        out.write(foot);
        out.flush();
        out.close();
        //请求成功后在响应流中拿结果
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        try {
            //定义bufferedreader输入流来读取url相应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null){
                buffer.append(line);
            }
            if(result == null){
                result = buffer.toString();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(reader != null){
                reader.close();
            }
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        logger.info("上传文件结果:"+jsonObject);
        String mediaId = jsonObject.getString("media_id");
        return mediaId;
    }
}
